package com.imchen.cms.cmscore.service;

import com.imchen.cms.cmscore.model.WebFile;
import com.imchen.cms.cmscore.dao.WebFileMapper;
import com.imchen.cms.exception.CmsException;
import com.imchen.cms.utils.ServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author imchen
 * @create: 2019-01-16 17:26
 **/
@Service
public class WebFileService implements BaseService<WebFile> {

    private Logger logger= LoggerFactory.getLogger(this.getClass());

    @Value("${cms.upload.path}")
    private String savePath;

    @Value("${cms.host}")
    private String host;

    @Autowired
    private WebFileMapper mapper;

    @Override
    public HashMap<String, Integer> add(WebFile webFile) {
        int count = mapper.insertSelective(webFile);
        return ServiceUtil.toAddMap(count,webFile.getId());
    }

    @Override
    public WebFile findById(int id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public int removeById(int id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int deleteById(int id) {
        return 0;
    }

    @Override
    public int update(WebFile webFile) {
        return mapper.updateByPrimaryKeySelective(webFile);
    }

    public WebFile upload(MultipartFile file) throws CmsException {
        if (file.isEmpty()){
            return null;
        }
        File saveDir= new File(savePath);
        if(!saveDir.exists()){
            boolean madeDir=saveDir.mkdirs();
            if (!madeDir){
                throw new CmsException("Directory create failed! Please check you upload path permission",500);
            }
        }
        WebFile webFile = null;
        ApplicationHome home=new ApplicationHome(getClass());
        String fileName = file.getOriginalFilename();
        fileName=UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
        File dest =new File(savePath+"/"+fileName);
        try {
            file.transferTo(dest);
            webFile=new WebFile();
            webFile.setUrl(host+"/api/file/"+fileName);
            add(webFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CmsException("上传文件错误",500);
        }
        return webFile;
    }

    public int download(HttpServletResponse response,String fileName) throws CmsException {
        if (fileName.isEmpty()){
            return 0;
        }
//        File file =new File(FileUtil.getJarRunDirectory()+"/upload/"+fileName);
        File file =new File(savePath+"/"+fileName);
        if (file.exists()|| file.isDirectory()){
            throw new CmsException("未找到文件!",4041);
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return 1;
    }

    public ResponseEntity<Resource> view(String fileName) throws CmsException, FileNotFoundException {
        String filePath = savePath+"/"+fileName;
        return ServiceUtil.view(filePath);
    }


}